import {emit} from './Events'
export default class IndexDbStorage{
  DB_NAME = 'vom';
  DB_VERSION = 1;
  TABLE_NAME = 'indexDbStorage';
  constructor() {
    let request = window.indexedDB.open(this.DB_NAME, this.DB_VERSION);
    request.onerror = (e) => {};
    request.onsuccess = (e) => {};
    request.onupgradeneeded = (e) => {
      const db = e.target.result;
      let storeNames = db.objectStoreNames;
      if (!storeNames.contains(this.TABLE_NAME)) {
        const projectStore = db.createObjectStore(this.TABLE_NAME,{
          keyPath: 'key',
          autoIncrement: false,
        });
        projectStore.createIndex('key', 'key', { unique: false });
      }
    }
  }
  openDb = (callback)=>{
    let request = window.indexedDB.open(this.DB_NAME, this.DB_VERSION+1);
    request.onupgradeneeded = (e) => {
      console.log('onupgradeneeded')
      const db = e.target.result;
      let storeNames = db.objectStoreNames;
      if (!storeNames.contains(this.TABLE_NAME)) {
        const projectStore = db.createObjectStore(this.TABLE_NAME,{
          keyPath: 'key',
          autoIncrement: false,
        });
        projectStore.createIndex('key', 'key', { unique: false });
      }
    }
    request.onerror = (e) => {};
    request.onsuccess = (e) => {
      const db = e.target.result;
      callback(db)
    }
  }
  getItem(key,callback){
    this.openDb((db)=>{
      let objectStore = db.transaction(this.TABLE_NAME).objectStore(this.TABLE_NAME);
      let request = objectStore.index('key').get(key);
      request.onsuccess = (e) => {
        let result = e.target.result;
        if (result) {
          callback(result.value)
        }
      };
    })

  }

  removeItem(key) {
    this.openDb((db)=>{
      let objectStore = db.transaction(this.TABLE_NAME, 'readwrite').objectStore(this.TABLE_NAME);
      let request = objectStore.delete(key);
      request.onsuccess = (e) => {
        console.log('数据删除成功');
        emit(key,null)
      };
    })
  }

  setItem(key, value) {
    this.openDb((db)=>{
      let request = db.transaction(this.TABLE_NAME, 'readwrite')
        .objectStore(this.TABLE_NAME)
        .put({key,value});
      request.onsuccess = function (event) {
        console.log('数据写入成功');
        emit(key,JSON.parse(value))
      };
      request.onerror = function (event) {
        console.log('数据写入失败', event);
      };
    })
  }

}
